<template>
  <div>
    <el-form
      ref="ruleForm"
      :model="ruleForm"
      status-icon
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="账号：">
        <el-input v-model="ruleForm.username" type="text" autocomplete="off" />
      </el-form-item>
      <el-form-item label="姓名：">
        <el-input
          v-model="ruleForm.name"
          type="text"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="手机号：">
        <el-input v-model.number="ruleForm.phone" />
      </el-form-item>
      <el-form-item label="性别：">
        <el-radio-group v-model="ruleForm.sex" size="medium">
          <el-radio border label="1">男</el-radio>
          <el-radio border label="0">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="身份证号：">
        <el-input v-model.number="ruleForm.idNumber" />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="submitForm('ruleForm')"
        >保存</el-button>
        <el-button @click="resetForm('ruleForm')">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { addEmployee, queryEmployeeById, editEmployee } from '@/api/employee'
export default {
  data() {
    return {
      ruleForm: {
        sex: '1'
      }
    }
  },
  computed: {
    ifEdit() {
      return !!this.$route.params.id
    }
  },
  async mounted() {
    if (this.ifEdit) {
      this.ruleForm = await queryEmployeeById(this.$route.params.id)
    }
  },
  methods: {
    // 提交表单,新增或者修改
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.ifEdit) {
            editEmployee(this.ruleForm).then(() => {
              this.$message.success('编辑成功')
              this.$router.go(-1)
            })
          } else {
            addEmployee(this.ruleForm).then(() => {
              this.$message.success('添加成功')
              this.$router.go(-1)
            })
          }
        } else {
          return false
        }
      })
    },
    // 退出清空表单
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.$router.go(-1)
    }
  }
}
</script>

<style>
</style>
